﻿using PLCS.Domain.Logs;
using PLCS.Domain.Shared.Equipments;
using PLCS.EquipmentService.BackgroundWorks.Analysis;
using PLCS.Shared.Common.Constant;
using PLCS.SocialHttpClient.AGV;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PLCS.EquipmentService.BackgroundWorks
{
    [DisallowConcurrentExecution] // 禁止并行操作特性
    public class AGVInitalStatusWorker : QuartzBackgroundWorkerBase
    {
        private readonly AGVSocialService _aGVSocialService;
        private readonly IEquipmentRepository _equipmentRepository;
        private readonly ErrorLogManager _errorLogManager;

        public AGVInitalStatusWorker(AGVSocialService aGVSocialService, IEquipmentRepository equipmentRepository, ErrorLogManager errorLogManager)
        {
            JobDetail = JobBuilder.Create<AGVInitalStatusWorker>().WithIdentity(nameof(AGVInitalStatusWorker)).Build();
            Trigger = TriggerBuilder.Create().WithIdentity(nameof(AGVInitalStatusWorker))
                 .WithSimpleSchedule(s => s.WithIntervalInSeconds(1)
                 .WithMisfireHandlingInstructionIgnoreMisfires())
                 .Build();

            ScheduleJob = async scheduler =>
            {
                await scheduler.ScheduleJob(JobDetail, Trigger);
            };
            _aGVSocialService = aGVSocialService;
            _equipmentRepository = equipmentRepository;
            _errorLogManager = errorLogManager;
        }

        public override async Task Execute(IJobExecutionContext context)
        {
            var res = await _aGVSocialService.GetEquipmentsStatusAsync();

            if (res.Header.Code == "S")
            {
                var agvs = res.Body;
                foreach (var item in agvs)
                {
                    var equipment = await _equipmentRepository.GetByEquipmentNoAsync(item.EquipmentNo);
                    if (equipment != null)
                    {
                        equipment.OnlineStatus = (OnlineMode)Enum.Parse(typeof(OnlineMode), item.OnlineMode.ToString());
                        equipment.Status = (DeviceStatus)Enum.Parse(typeof(DeviceStatus), item.Status.ToString());
                        await _equipmentRepository.UpdateAsync(equipment);
                    }
                }
            }
            else
            {
                await _errorLogManager.AddErrorLogAsync(new ErrorLog("AGV", $"AGV设备状态获取失败：{res.Header.Message}", "AGV", "通讯"));
            }
        }
    }
}